package com.shop.shop_end.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.shop_end.entity.Cate;
import com.shop.shop_end.entity.Good;
import com.shop.shop_end.exception.ServiceException;
import com.shop.shop_end.mapper.GoodMapper;
import com.shop.shop_end.service.CateService;
import com.shop.shop_end.service.GoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.shop_end.utils.DateUtils;
import com.shop.shop_end.utils.GenerateIdUtil;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import com.shop.shop_end.variable.EnableVariable;
import com.shop.shop_end.variable.ErrorCodeEnum;
import com.shop.shop_end.vo.GoodVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2024-04-23
 */
@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good> implements GoodService {
    final Logger logger = LoggerFactory.getLogger(GoodServiceImpl.class);

    @Resource
    private GoodMapper goodMapper;

    @Resource
    private CateService cateService;

    /**
     * 增加一个good
     * @param good
     * @return
     */
    @Override // 继承接口的新增 返回值0(失败),1(成功)
    @Transactional
    public Result addOneGood(Good good) {
        good.setGoodId(GenerateIdUtil.generateId());
        good.setSellNum(0L);
        good.setCreateTime(new Date());
        good.setHits(0L);
        System.out.println("goodInfo==> "+good);
        List<Cate> allCate = cateService.getAllCate();
        Optional<Cate> cate = allCate.stream().filter((item)->
                item.getCateId() == good.getCateId()
        ).findFirst();
        String cateName = cate.get().getCateName();
        good.setCateName(cateName);
        logger.info("开始增加一个good,good==>{}", good);
        try {
            int insert = this.goodMapper.insert(good);
            if (insert == EnableVariable.UNABLE){
                logger.info("增加good出现异常");
                return ResultUtil.fail("增加good出现异常");
            }
        }catch (Exception e){
            logger.info("增加good出现异常");
            throw new ServiceException(ErrorCodeEnum.SQL_INSERT_ERROR, "增加good出现异常");
        }
        logger.info("增加成功");
        return ResultUtil.ok("增加成功");
    }

    /**
     * 修改good信息
     * @param good
     * @return
     */
    @Override // 继承接口的更新 返回值0(失败),1(成功)
    @Transactional
    public Result updateGood(Good good) {
        List<Cate> allCate = cateService.getAllCate();
        logger.info("updateGood==>{}", good);
//        Optional<Cate> cate = allCate.stream().filter((item)->
//                item.getCateId() == good.getCateId()
//        ).findFirst();
        Cate cate = new Cate();
        allCate.forEach((item)->{
            logger.info("item==>{}", item);
            if (ObjectUtil.equal(item.getCateId(), good.getCateId())){
                logger.info("cate==>{}", item);
                String cateName = item.getCateName();
                good.setCateName(cateName);
            }
        });
        logger.info("开始修改good信息,good==>{}", good);
        try {
            int update = this.goodMapper.updateById(good);
            if (update == EnableVariable.UNABLE){
                logger.info("修改good失败");
                return ResultUtil.fail("修改good出现异常");
            }
        }catch (Exception e){
            logger.info("修改good失败");
            throw new ServiceException(ErrorCodeEnum.SQL_DELETE_ERROR, "修改good出现异常");
        }
        logger.info("修改成功");
        return ResultUtil.ok("修改成功");
    }


    /**
     * 根据id删除good
     * @param goodId
     * @return
     */
    @Override // 继承接口的删除 返回值0(失败),1(成功)
    public Result deleteGoodById(Long goodId) {
        try {
            logger.info("goodId==>{}", goodId);
            logger.info("开始删除good");
            int delete = this.goodMapper.deleteById(goodId);
            if (delete == EnableVariable.UNABLE){
                logger.info("删除good失败");
                return ResultUtil.fail("删除good失败");
            }
        }catch (Exception e){
            logger.info("删除id为==>{}的good出现异常", goodId);
            throw new ServiceException(ErrorCodeEnum.SQL_DELETE_ERROR, "删除good出现异常");
        }
        logger.info("删除成功");
        return ResultUtil.ok("删除成功");
    }

    /**
     * 获取所有good
     * @return
     */
    @Override // 继承接口的查询全部
    public List<GoodVo> getAllGoods() {
        List<Good> goodList = this.goodMapper.selectList(new QueryWrapper<Good>());
        List<GoodVo> goodVoList = new ArrayList<>();
        if (goodList.size() != 0){
            goodList.forEach((item)->{
                GoodVo goodVo = new GoodVo();
                goodVo.setGoodId(item.getGoodId());//id
                goodVo.setGoodName(item.getGoodName());//货物名称
                goodVo.setCateId(item.getCateId());//分类id
                goodVo.setCateName(item.getCateName());//分类名称
                goodVo.setContents(item.getContents());//内容
                goodVo.setCreateTime(DateUtils.format(item.getCreateTime()));//时间
                goodVo.setRecommend(item.getRecommend());//推荐
                goodVo.setImage(item.getImage());//图片
                goodVo.setHits(item.getHits());//点击数
                goodVo.setPrice(item.getPrice());//价格
                goodVo.setSellNum(item.getSellNum());//已售卖数量
                goodVo.setSpecial(item.getSpecial());//特价
                goodVo.setStorage(item.getStorage());//库存
                goodVoList.add(goodVo);
            });
        }
        return goodVoList;
    }

    /**
     * 根据分类查找所有good
     * @param cateId
     * @return
     */
    @Override // 继承接口的查询全部
    public Result getGoodsByCate(Long cateId) {
        QueryWrapper<Good> wrapper = new QueryWrapper<>();
        logger.info("开始根据分类来查找good，cateId==>{}", cateId);
        wrapper.eq("cateId", cateId);
        List<Good> goodList = this.goodMapper.selectList(wrapper);
        logger.info("goodList==>{}", goodList);
        return ResultUtil.ok(goodList);
    }

    /**
     * 根据点击数降序显示goodList
     * @return
     */
    @Override // 继承接口的查询全部
    public Result getGoodsByHit() {
        QueryWrapper<Good> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("hits");
        List<Good> goodList = this.goodMapper.selectList(wrapper);
        logger.info("goodList==>{}", goodList);
        return ResultUtil.ok(goodList);
    }


    /**
     * 根据id查询出货物详情
     * @param goodId
     * @return
     */
    @Override // 继承接口的按主键查询 返回Entity实例
    public GoodVo getGoodsById(Long goodId) {
        Good good = this.goodMapper.selectById(goodId);
        GoodVo goodVo = new GoodVo();
        goodVo.setGoodId(good.getGoodId());//id
        goodVo.setGoodName(good.getGoodName());//货物名称
        goodVo.setCateId(good.getCateId());//分类id
        goodVo.setCateName(good.getCateName());//分类名称
        goodVo.setContents(good.getContents());//内容
        goodVo.setCreateTime(DateUtils.format(good.getCreateTime()));//时间
        goodVo.setRecommend(good.getRecommend());//推荐
        goodVo.setImage(good.getImage());//图片
        goodVo.setHits(good.getHits());//点击数
        goodVo.setPrice(good.getPrice());//价格
        goodVo.setSellNum(good.getSellNum());//已售卖数量
        goodVo.setSpecial(good.getSpecial());//特价
        goodVo.setStorage(good.getStorage());//库存
        return goodVo;
    }

}
